package com.example.bankseckill.task;

/**
 * @Author: liyangjing
 * @Date: 2022/03/03/9:57
 * @Description:
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.bankseckill.pojo.SecKillMessageConstants;
import com.example.bankseckill.pojo.SeckillmessageLog;
import com.example.bankseckill.service.ISeckillmessageLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息日志定时检测任务
 */
@Component
public class MQTask {

    @Autowired
    private ISeckillmessageLogService seckillmessageLogService;


    private RabbitTemplate rabbitTemplate;

    /**
     * 消息发送定时检查任务
     * 10秒一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask() {
        //状态为0且重试时间小于当前时间的才需要重新发送
        List<SeckillmessageLog> list = seckillmessageLogService.list(new QueryWrapper<SeckillmessageLog>().eq("status", 0).lt("tryTime",
                LocalDateTime.now()));
        list.forEach(seckillmessageLog -> {
            //重试次数超过3次，更新为投递失败，不再重试
            if (3 <= seckillmessageLog.getCount()) {
                seckillmessageLogService.update(new UpdateWrapper<SeckillmessageLog>().set("status", 2).eq("msgId", seckillmessageLog.getMsgId()));
            }
            //更新重试次数，更新时间，重试时间
            seckillmessageLogService.update(new UpdateWrapper<SeckillmessageLog>().set("count",seckillmessageLog.getCount()+1).set("updateTime",LocalDateTime.now()).set("tryTime",LocalDateTime.now().plusMinutes(SecKillMessageConstants.MSG_TIMEOUT)).eq("msgId",seckillmessageLog.getMsgId()));
            //发送消息
            rabbitTemplate.convertAndSend(SecKillMessageConstants.EXCHANGE_NAME, SecKillMessageConstants.ROUTING_KEY_NAME,seckillmessageLog,
                    new CorrelationData(seckillmessageLog.getMsgId()));
        });
    }
}
